package com.agricultural.machine.path;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 绕行路径策略 - 策略模式
 */
public class AvoidObstaclePathStrategy implements PathStrategy {
    private final Random random = new Random();
    
    @Override
    public String getName() {
        return "绕行路径";
    }

    @Override
    public String getDescription() {
        return "绕行路径策略 - 考虑障碍物的路径规划，在障碍处绕行";
    }

    @Override
    public List<PathPoint> calculatePath(PathPoint start, PathPoint end, TerrainData terrain) {
        List<PathPoint> path = new ArrayList<>();
        path.add(start);
        
        // 模拟障碍物
        int obstacleCount = 2 + random.nextInt(3);
        List<PathPoint> obstacles = new ArrayList<>();
        for (int i = 0; i < obstacleCount; i++) {
            double ratio = 0.2 + random.nextDouble() * 0.6;
            double x = start.x + (end.x - start.x) * ratio;
            double y = start.y + (end.y - start.y) * ratio;
            obstacles.add(new PathPoint(x, y));
        }
        
        System.out.println("检测到 " + obstacleCount + " 个障碍物");
        for (int i = 0; i < obstacles.size(); i++) {
            PathPoint obstacle = obstacles.get(i);
            System.out.println("障碍物 " + (i + 1) + ": " + obstacle);
        }
        
        // 绕行障碍物
        double lastX = start.x;
        double lastY = start.y;
        
        for (PathPoint obstacle : obstacles) {
            // 先向障碍物的一侧移动
            double offsetX = (obstacle.y - lastY) * 0.5;
            double offsetY = (lastX - obstacle.x) * 0.5;
            
            // 防止偏移太小
            if (Math.abs(offsetX) < 5 && Math.abs(offsetY) < 5) {
                offsetX = offsetX < 0 ? -5 : 5;
                offsetY = offsetY < 0 ? -5 : 5;
            }
            
            // 添加绕行点
            double x1 = (lastX + obstacle.x) / 2 + offsetX;
            double y1 = (lastY + obstacle.y) / 2 + offsetY;
            path.add(new PathPoint(x1, y1));
            
            double x2 = obstacle.x + offsetX;
            double y2 = obstacle.y + offsetY;
            path.add(new PathPoint(x2, y2));
            
            lastX = x2;
            lastY = y2;
        }
        
        // 添加最后一段到终点的路径
        double distance = Math.sqrt(Math.pow(end.x - lastX, 2) + Math.pow(end.y - lastY, 2));
        int pointCount = (int)(distance / 10) + 1;
        
        for (int i = 1; i < pointCount; i++) {
            double ratio = i / (double)pointCount;
            double x = lastX + (end.x - lastX) * ratio;
            double y = lastY + (end.y - lastY) * ratio;
            path.add(new PathPoint(x, y));
        }
        
        path.add(end);
        
        System.out.println("使用绕行路径策略计算从 " + start + " 到 " + end + " 的路径");
        System.out.println("生成路径点数量: " + path.size());
        
        return path;
    }
} 